package com.fruit.service.account;

import com.joe.utils.cluster.lock.ClusterLock;
import com.joe.utils.cluster.lock.RedisClusterLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author joe
 */
@Service
@Slf4j
public class LockManager {
    @Value("${redis.port}")
    private int port;
    @Value("${redis.host}")
    private String host;
    @Value("${redis.password}")
    private String password;

    private RedissonClient client;

    @PostConstruct
    public void init() {
        try {
            log.debug("初始化锁服务，redis地址是：{}，端口是：{}", host, port);
            if (host == null || "".equals(host.trim()) || port <= 0) {
                log.debug("当前没有redis信息");
                return;
            }
            Config config = new Config();
            config.useSingleServer().setAddress(host + ":" + port).setPassword(password);
            this.client = Redisson.create(config);
            log.debug("初始化的分布式管理器为：{}", this.client);
        } catch (Exception e) {
            log.debug("锁服务初始化失败", e);
        }
    }

    /**
     * 获取分布式锁
     *
     * @param lockName 锁名称
     * @return 获取成功返回锁，获取失败返回null
     */
    public ClusterLock getLock(String lockName) {
        if (client != null) {
            return new RedisClusterLock(client.getLock(lockName));
        } else {
            return null;
        }
    }
}
